﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : MultiServerEngine | ServerFramework | ClientRequestForwardHandler.cs
// //  Created : 2016 - 02 - 16 20:53
// //  Modified: 2016 - 02 - 20 12:33
// //  ********************************************************************************

using System.Linq;
using ExitGames.Logging;
using ServerFramework.Implementation.Server;
using ServerFramework.Interfaces.Client;
using ServerFramework.Interfaces.Server;
using ServerFramework.Interfaces.Telegram;
using TypeDefs;

namespace ServerFramework.Implementation.Handler.Forward
{
    public class ClientRequestForwardHandler : ClientTelegramHandler
    {
        private IServerPeerRegistry<IServerPeer> ServerPeerRegistry { get; }

        public override TelegramHandlerTypes HandlerType => TelegramHandlerTypes.Request;
        public override byte Code => (byte) OperationCodes.ForwardRequest;
        public override int? SubCode => null;

        public ClientRequestForwardHandler(ILogger logger, IServerPeerRegistry<IServerPeer> serverPeerRegistry)
            : base(logger)
        {
            ServerPeerRegistry = serverPeerRegistry;
        }

        public override bool HandleTelegram(ITelegram telegram, IClientPeer clientPeer)
        {
            Logger.InfoFormat("Handling forwarding request from client peer with id={0}", clientPeer.PeerId);

            ServerPeer peer =
                ServerPeerRegistry.GetServerPeers()
                    .Values.FirstOrDefault(
                        c =>
                            c.GetHandledOperations()[HandlerTypes.ServerHandler].Contains((OperationCodes) telegram.Code))
                    as ServerPeer;

            if (peer != null)
            {
                telegram.Parameters.Add((byte) ParameterCodes.PeerId, clientPeer.PeerId.ToString());
                telegram.Parameters.Add((byte) ParameterCodes.PeerType, peer.ServerType);

                Logger.InfoFormat("Found responsible server {0}....forwarding", peer.ServerType);
                peer.SendTelegram(telegram);
                return true;
            }

            return false;
        }
    }
}
